<?php
// +----------------------------------------------------------------------
// | 卡券
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\controller\api\v3;

use app\event\app\Jd;
use app\event\app\Pdd;
use app\event\app\Tbk;
use app\event\ucenter\Feedback as FeedbackEvent;
use app\model\app\JdGood as JdGoodModel;
use app\model\app\Modular as ModularModel;
use app\model\app\PddGood as PddGoodModel;
use app\model\app\TbkOrder as TbkOrderModel;
use app\model\app\RebateKeyword as RebateKeywordModel;
use app\model\app\JdOrder as JdOrderModel;
use app\event\app\Rebate as RebateEvent;
use think\facade\Db;

class Rebate extends Common
{


    public function parse()
    {
        $content = $this->request->param('content');
        $channel = $this->request->param('channel', 'tbk');
        $from = $this->request->param('from', 'link');
        $event = new RebateEvent();
        $re = $event->parseContent($content, $this->user, $channel, $from);
        return $this->successAjax($re);
    }

    public function order()
    {
        if ($this->request->isPost()) {

            $data = $this->request->param();

            $result = $this->validate($this->request->post(), 'app\validate\ucenter\Feedback');
            if (true !== $result) {
                $data['code'] = 20002;
                $data['message'] = $result;
            } else {
                $user_event = new FeedbackEvent();
                $data = $user_event->add($this->request->param(), $this->user);
            }

            return $this->autoAjax($data);
        } else {
            $info = [];
            $info['lists']['tbk'] = '淘宝/天猫';
            $info['lists']['jd'] = '京东';
            $info['lists']['pdd'] = '拼多多';
            $info['tips'] = '暂时支持一单提交';
            $info['image'] = 1;
            return $this->successAjax($info);
        }

    }


    /**
     * 优惠券主页
     */
    public function home()
    {
        $data['modular'] = ModularModel::with('cover')->where('id', 11)->find();
        $data['channel']['tbk'] = 1;
        $data['channel']['pdd'] = 1;
        $data['channel']['jd'] = 0;
        $avg = TbkOrderModel::where('status', 1)->order('id DESC')->limit(10)->avg('income_rate');
        $data['show_text_tips'] = '近期购物平均返' . round($avg, 2) . '%';
        $data['fee']['tbk'] = config('tbk.add_fee');
        $data['explosiveGoods'] = [];
        if ($this->user) {
            $data['pdd_ok'] = PddGoodModel::where('user_id', $this->user['id'])
                ->whereTime('update_time', '>', '-1 day')
                ->whereNotNull('mobile_short_url')
                ->whereRaw('`check_ok_time` > \'' . time_format() . '\' OR `check_ok_time` IS NULL')
//                ->whereTime('check_ok_time', '>', 'today')
                ->order('id DESC')->limit(50)
                ->where('status', 1)->select();
        } else {
            $data['pdd_ok'] = [];
        }
        $page = $this->request->param('page', 1);
        //榜单类型：1.实时榜 ，2.全天榜，3.热推榜，7.综合热搜榜，8.原实时榜2.0（已升级为实时榜），9.必推榜，11.昨日销量榜，12.7日销量榜，13.30日销量榜，14.去年同期销量榜，15.低价高佣榜。红色为2024/05/15新增榜单
        $data['tabs'][] = ['id' => 7, 'name' => '综合榜'];
        $data['tabs'][] = ['id' => 1, 'name' => '实时榜'];
        $data['tabs'][] = ['id' => 15, 'name' => '高佣榜'];
        $data['tabs'][] = ['id' => 11, 'name' => '昨日榜'];
        $data['tabs'][] = ['id' => 9, 'name' => '必推榜'];
        $my_count = 0;
        if ($this->user)
        {
            $my_count = JdOrderModel::where('status', 1)->where('user_id',$this->user['id'])->whereTime('create_time', 'month')->count();
        }
        if ($my_count>=2)
        {
            $data['tabs_jd'] = ['id' => -1, 'name' => '全额返'];
            $tab_id = $this->request->param('tab_id', 7);
        }else{
            $data['tabs_jd'] = ['id' => 0, 'name' => '全额返'];
            $tab_id = $this->request->param('tab_id', 0);
        }
        $left = 30 - JdOrderModel::where('status', 1)->whereTime('create_time', 'month')->count();

        $data['tab_id'] = $tab_id;
//        $data['jd_goods'] =  JdGoodModel::where('status',1)->limit(5)->select();
        $data['jd_goods'][] = [
            'img' => 'https://img14.360buyimg.com/n1/jfs/t1/260282/31/17239/42096/67a499f4F2f77370b/400b2114a6200d92.jpg',
            'price' => '2.00',
            'low_fee' => '2.00',
            'material_url' => 'https://u.jd.com/z1VuezS',
            'has_num' => $left,
            'title' => '家具整理创意壁挂置物架子帽子收纳挂钩免打孔家衣',
            'shop_name' => '京喜自营官方店',
        ];
        $data['jd_goods'][] = [
            'img' => 'https://img14.360buyimg.com/n1/jfs/t1/266423/9/17129/145908/67a46e81F2538db0d/7d1d7e31ca9e767f.jpg',
            'low_fee' => '2',
            'price' => '1.95',
            'material_url' => 'https://u.jd.com/zg7FM99',
            'has_num' => $left,
            'title' => '医用外科口罩50片独立装三层防护口罩一次性防细菌透气支原体 独立灭菌(10片)',
            'shop_name' => '京喜自营官方店',
        ];
        $data['jd_goods'][] = [
            'img' => 'https://img14.360buyimg.com/n1/jfs/t1/88483/5/38544/106261/64794633F4dc8a21a/2e2c3de393372df0.jpg',
            'low_fee' => '2',
            'price' => '1.79',
            'material_url' => 'https://u.jd.com/zg75XnM',
            'has_num' => $left,
            'title' => '居品家高分子细滑牙线棒家庭装一次性牙线便携盒装 牙线棒1盒50根',
            'shop_name' => '韩多多清洁用品店',
        ];
        $data['jd_goods'][] = [
            'img' => 'https://img14.360buyimg.com/n1/jfs/t1/256491/33/15675/100527/67a492b6Fd5652647/3ab17fe714a35fba.jpg',
            'low_fee' => '2',
            'price' => '2',
            'material_url' => 'https://u.jd.com/zr7m26U',
            'has_num' => $left,
            'title' => '迪士尼婴儿手口湿巾卸妆湿巾草莓熊湿巾40抽新生儿宝宝手口湿巾3 厚款 40抽 【加厚】1大包',
            'shop_name' => '京喜自营官方店',
        ];
        $data['jd_goods'][] = [
            'img' => 'https://img14.360buyimg.com/n1/jfs/t1/248689/32/28421/73555/67554036Fd421fa20/982e055012c933d5.jpg',
            'low_fee' => '2',
            'price' => '2.1',
            'material_url' => 'https://u.jd.com/zO74ijj',
            'has_num' => $left,
            'title' => '漫花家用纸巾抽纸实惠装餐巾纸卫生纸家庭装婴儿擦手 爆款蓝色【400张*1包】',
            'shop_name' => '漫花清洁纸品旗舰店',
        ];

        if ($tab_id > 0) {
            $tbk = new Tbk();
            $re = $tbk->getRankingList($tab_id, $page);
            if ($re['code'] == 0) {
                $data['topGoods'] = $re['data'];
            }
        } else {
            $data['topGoods'] = [];
        }
        return $this->successAjax($data);
    }

    /**
     * 优惠券主页
     */
    public function search()
    {
        if ($this->request->isPost()) {
            $keyword = $this->request->param('keyword', '');
            if (empty($keyword)) {
                return $this->errorAjax('请输入关键词');
            } else {

                RebateKeywordModel::create(['keyword' => $keyword, 'user_id' => $this->user['id']]);
                $tab_id = $this->request->param('tab_id', 0);
                $page = $this->request->param('page', 1);
                $goods = [];
                if ($tab_id == 0) {
                    // 全网搜索
                    $pdd = new Pdd();
                    $pddGoods = $pdd->searchByKeyword($keyword, $this->user, $page);
                    $tbk = new Tbk();
                    $tbkGoods = $tbk->searchByKeyword($keyword, $this->user, $page);
                    $jd = new Jd();
                    $jdGoods = $jd->searchByKeyword($keyword, $this->user, $page);
                } elseif ($tab_id == 2) {
                    $pdd = new Pdd();
                    $pddGoods = $pdd->searchByKeyword($keyword, $this->user, $page);
                } elseif ($tab_id == 1) {
                    $tbk = new Tbk();
                    $tbkGoods = $tbk->searchByKeyword($keyword, $this->user, $page);
                } elseif ($tab_id == 3) {
                    $jd = new Jd();
                    $jdGoods = $jd->searchByKeyword($keyword, $this->user, $page);
                } else {
                    return $this->errorAjax('参数异常');
                }
                for ($i = 0; $i < 50; $i++) {
                    if (isset($pddGoods['data'][$i])) {
                        $goods[] = RebateEvent::formatGood($pddGoods['data'][$i], 'pdd');
                    }
                    if (isset($tbkGoods['data'][$i])) {
                        $goods[] = RebateEvent::formatGood($tbkGoods['data'][$i], 'tbk');
                    }
                    if (isset($jdGoods['data'][$i])) {
                        $goods[] = RebateEvent::formatGood($jdGoods['data'][$i], 'jd');
                    }
                }
            }
            $data['modular'] = ModularModel::with('cover')->where('id', 11)->find();
            $data['channel']['tbk'] = 1;
            $data['channel']['pdd'] = 1;
            $data['channel']['jd'] = 0;

            $data['tabs'][] = ['id' => 0, 'name' => '全网比价'];
            $data['tabs'][] = ['id' => 1, 'name' => '淘宝'];
            $data['tabs'][] = ['id' => 2, 'name' => '拼多多'];
            $data['tabs'][] = ['id' => 3, 'name' => '京东'];
            $data['goods']['data'] = $goods;
            $data['goods']['current_page'] = 1;
            $data['goods']['total'] = 50;

            return $this->successAjax($data);
        } else {
            $data['modular'] = ModularModel::with('cover')->where('id', 11)->find();
            $data['channel']['tbk'] = 1;
            $data['channel']['pdd'] = 1;
            $data['channel']['jd'] = 1;

            $data['fee']['tbk'] = config('tbk.add_fee');
            $data['keywords'] = ['红米K80', '华为', 'iphone', '湿巾', '垃圾桶'];

            if ($this->user) {
                $keywords = Db::name('rebate_keyword')
                    ->limit(10)
                    ->order('id DESC')
                    ->where('user_id', $this->user['id'])->field('keyword')->whereTime('create_time', '>', '-10 day')->distinct(true)->column('keyword');
                if (!empty($keywords)) {
                    if (count($keywords) < 5) {
                        $data['keywords'] = $keywords;
                    } else {
                        $data['keywords'] = array_unique(array_merge($keywords, $data['keywords']));
                    }
                }
            }
            //榜单类型：1.实时榜 ，2.全天榜，3.热推榜，7.综合热搜榜，8.原实时榜2.0（已升级为实时榜），9.必推榜，11.昨日销量榜，12.7日销量榜，13.30日销量榜，14.去年同期销量榜，15.低价高佣榜。红色为2024/05/15新增榜单
            $data['tabs'][] = ['id' => 0, 'name' => '全网比价'];
            $data['tabs'][] = ['id' => 1, 'name' => '淘宝'];
            $data['tabs'][] = ['id' => 2, 'name' => '拼多多'];
            $data['tabs'][] = ['id' => 3, 'name' => '京东'];

            return $this->successAjax($data);
        }

    }


}
